package xyz.jcat.biz.member.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import xyz.jcat.auth.token.AccessTokenUtils;
import xyz.jcat.auth.token.UserTokenDto;
import xyz.jcat.biz.member.domain.dto.LoginDto;
import xyz.jcat.biz.member.domain.po.MemberPo;
import xyz.jcat.biz.member.domain.vo.LoginSuccessVo;
import xyz.jcat.biz.member.service.ILoginService;
import xyz.jcat.biz.member.service.IMemberService;
import xyz.jcat.common.util.CodeUtils;
import xyz.jcat.common.util.RSAUtils;
import xyz.jcat.common.web.RespCodeMsg;

import java.util.Arrays;
import java.util.Objects;

@Service
public class LoginService implements ILoginService {

    private static final long ACCESS_TOKEN_CACHE_TIME_OUT = 60 * 60 * 24 * 7;
    @Autowired
    private IMemberService memberService;

    @Override
    public LoginSuccessVo login(LoginDto loginDto) {
        MemberPo member = memberService.getByPhone(loginDto.getPhone());
        //注册
        if(Objects.isNull(member)) {
            member = memberService.register(loginDto.getPhone(), loginDto.getPassword());
        }
        //登录
        else {
            //TODO 验证码
            //校验密码
            RespCodeMsg.PHONE_OR_PWD_ERROR.isFalse(
                    CodeUtils.checkPwd(RSAUtils.decrypt(loginDto.getPassword()), member.getPassword())
            );
        }
        //删除过去token
        AccessTokenUtils.removeAccessToken(member.getId());
        //TODO roles
        UserTokenDto userToken = new UserTokenDto(member.getId(), Arrays.asList(1L,2L));
        String accessToken = AccessTokenUtils.generateAccessToken(userToken, ACCESS_TOKEN_CACHE_TIME_OUT);
        return new LoginSuccessVo(accessToken, member);
    }

}
